﻿using System;
using System.Collections.Generic;
using System.Text;
using Slwy.Data.Entity.Interfaces;
using Slwy.EventBus.Interfaces;
using Slwy.EventBus.Models;
using Slwy.FrameCore.Helper;
using SqlSugar;
using Slwy.FrameCore.Extension;
using Slwy.Logger.Contracts;
using Slwy.Utility.Extensions;

namespace Slwy.EventBus.Contracts
{
    public class EventListen : IEventListen
    {
        public IDictionary<string, EventInfoEntity> PendEventInfos { get; set; } =
            new Dictionary<string, EventInfoEntity>();
        public ILogger Logger { get; set; }
        public ISlwyHttpClient HttpClient { get; set; }
        public IEventInfoRepository EventInfoRepo { get; set; }

        public bool OnSaveChanged(SqlSugarClient sqlSugarClient, string dbName)
        {
            var pendEventKey = sqlSugarClient.ContextID.ToString();
            if (!PendEventInfos.TryGetValue(pendEventKey, out var eventInfoEntity))
            {
                return false;
            }

            PendEventInfos.Remove(pendEventKey);

            try
            {
                var result = HttpClient.Post<MSendEventResult>("/api/eventbus/event", new
                {
                    eventInfoEntity.RoutingKey,
                    data = eventInfoEntity.Data,
                    delayTime = eventInfoEntity.DelayTime,
                    callBackType = "dynamic"
                });

                if (result.BusinessCode != 1)
                {
                    EventInfoRepo.UpdateEventInfoErrorMessage(sqlSugarClient.Ado.Connection.ConnectionString,
                        eventInfoEntity.KeyID, result.Message);
                    Logger.Error($"发送事件失败: {result.Message}", context: eventInfoEntity.ToJson());
                    return false;
                }
            }
            catch (Exception e)
            {
                EventInfoRepo.UpdateEventInfoErrorMessage(sqlSugarClient.Ado.Connection.ConnectionString,
                    eventInfoEntity.KeyID, e.Message);
                Logger.Error($"发送事件失败: {e}", context: eventInfoEntity.ToJson());
                return false;

            }

            EventInfoRepo.UpdateEventInfoForPosted(sqlSugarClient.Ado.Connection.ConnectionString,  eventInfoEntity.KeyID);

            return true;
        }
    }
}
